<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/4/20
 * Time: 15:41
 */

namespace common\logics\expressorder;

use common\widgets\Tool;
use Yii;
use yii\base\BaseObject;

class ExpressOrderLogic extends BaseObject implements IExpressOrder
{
    /** @var \common\sources\read\taskorder\TaskOrderAccess  $RTaskOrderAccess **/
    private $RTaskOrderAccess;
    /** @var \common\sources\write\taskorder\TaskOrderAccess $WTaskOrderAccess  **/
    private $WTaskOrderAccess;
    /** @var \common\sources\read\shop\ShopAccess $RShopAccess **/
    private $RShopAccess;
    /** @var \common\sources\read\valueservice\ValueServiceAccess $RValueServiceAccess  **/
    private $RValueServiceAccess;
    /** @var \common\sources\write\taskorderlog\BuyTaskOrderLogAccess  $WBuyTaskOrderLogAccess  ***/
    private $WBuyTaskOrderLogAccess;


    public function init()
    {
        $this->RTaskOrderAccess = Yii::$container->get("RTaskOrderAccess");
        $this->WTaskOrderAccess = Yii::$container->get("WTaskOrderAccess");
        $this->RShopAccess = Yii::$container->get("RShopAccess");
        $this->RValueServiceAccess = Yii::$container->get("RValueServiceAccess");
        $this->WBuyTaskOrderLogAccess = Yii::$container->get("WBuyTaskOrderLogAccess");
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function printTaskOrder($data)
    {
        if(count($data['task_info']) == 0)
        {
            return Tool::returnJson([],401,"打印数据内容不能为空");
        }
        if(empty($data['operator']))
        {
            return Tool::returnJson([],402,"操作人不能为空");
        }
        $nums = "'".implode("','",$data['task_info'])."'";
        $task_orders = $this->RTaskOrderAccess->getTaskOrderByNum($nums);
        if(count($task_orders) == 0)
        {
            return Tool::returnJson([],403,"打印数据已经处理");
        }
//        if(count($data['task_info']) != count($task_orders))
//        {
//            return Tool::returnJson([],403,"待打印数据不一致");
//        }
//        $orderArr = array_column($task_orders,"order_status");
//        $res = array_unique($orderArr);
//        if(count($res)>1)
//        {
//            return Tool::returnJson([],405,"存在子订单状态不一致问题");
//        }
        //进行模拟打印处理
        $result = false;
        $transaction = Yii::$app->db->beginTransaction();
        try{
            foreach ($task_orders as $item)
            {
                //获取店铺信息
                $shop = $this->RShopAccess->getShopById($item['shop_id']);
                if(empty($shop))
                {
                    $transaction->rollBack();
                    return Tool::returnJson([],405,"店铺信息部存在");
                }
                $value_service = $this->RValueServiceAccess->getList($item['task_commod_id']);
                if(empty($value_service))
                {
                    $transaction->rollBack();
                    return Tool::returnJson([],406,"增值服务信息不存在");
                }
                $print_arr = [
                    "shop_order_num" => $item['pay_order_num'],
                    "receipter" => $item['receive_name'],
                    "rece_phone" => $item['receive_phone'],
                    "addr" => $item['pro_name']." ".$item['city_name']." ".$item['area_name']." ".$item['addr'],
                    "zip_code" => '',
                    "weight" => $value_service['weight'],
                    "trade_name" => $item['title'],
                    "send_name" => $shop['send_name'],
                    "send_phone" => $shop['send_phone'],
                    "send_provice" => $shop['pro_name'],
                    "send_city" => $shop['city_name'],
                    "send_area" => $shop['area_name'],
                    "send_addr" => $shop['addr'],
                    "plat_type" => $item['plat_type'],
//                    "express_type" => 10,
//                    "plat_type" => 1,
                    "plat_type" => $item['plat_type'],
                    "express_type" => $item['express_type'],
                ];
                //判断是否需要打印订单 如果不需要打印
                if(empty($item['express_type']))
                {
                    $result = $this->WTaskOrderAccess->printTaskOrderByNum(['order_status'=> 4,"express_num" => '',"task_order_id" => $item['id']]);
                    if(!$result)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],411,"打印没有快递子订单失败");
                    }
                    $arr = [
                        "buy_id" => $item['buy_id'],
                        "task_status" => 4,
                        "status_remark" => "后台已打印,待商家发货",
                        "remark" => "已打印待商家发货",
                        "task_order_id" => $item['id'],
                        "operator" => $data['operator'],
                    ];
                    $this->WBuyTaskOrderLogAccess->addTaskOrderLog($arr);
                }else
                 {
                     $push_url = Yii::$app->params['print_task_order_url'];
                     $arr = $this->http_post($push_url,$print_arr);
                     $json_arr = json_decode($arr,true);
                     if($json_arr['code'] == 200)
                     {
                         if(!empty($json_arr['data']['odd_num']))
                         {
                             $result = $this->WTaskOrderAccess->printTaskOrderByNum(['order_status'=> 4,"express_num" => $json_arr['data']['odd_num'],"task_order_id" => $item['id']]);
                             $arr = [
                                 "buy_id" => $item['buy_id'],
                                 "task_status" => 4,
                                 "status_remark" => "后台已打印,待商家发货",
                                 "remark" => "已打印待商家发货",
                                 "task_order_id" => $item['id'],
                                 "operator" => $data['operator'],
                             ];
                             $this->WBuyTaskOrderLogAccess->addTaskOrderLog($arr);
                         }else
                         {
                             return Tool::returnJson([],408,"没有打印单号,请联系客服");
                         }

                     }else
                     {
                         return Tool::returnJson([],409,$json_arr);
                     }
                 }
//                $express_num = rand(10000000,999999999);
//                $result = $this->WTaskOrderAccess->printTaskOrderByNum(['order_status'=> 4,"express_num" => $express_num,"task_order_id" => $item['id']]);
            }
            if(!$result)
            {
                $transaction->rollBack();
                return Tool::returnJson([],410,"存在异常打印订单");
            }
            $transaction->commit();
            return Tool::returnJson([],200,"成功");
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],5000,"打印异常".$e->getMessage());
        }
    }

    private function http_post($url,$param)
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }


}